package org.feng.resource;

import java.util.List;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.feng.entity.EntityPool;
import org.feng.entity.ServiceProvider;
import org.feng.entity.User;
import org.jboss.logging.Logger;

import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
public class UserRs {

	private static final Logger LOG = Logger.getLogger(SvrProviderRs.class);

	public UserRs() {

	}

	/**
	 * 查询用户
	 */
	// @Path("svr_list")
	@GET
	// @Produces(MediaType.APPLICATION_JSON)
	public RetMsg list(@QueryParam("type") String type, @QueryParam("status") String status,
			@QueryParam("userName") String name, @QueryParam("tel") String tel, @QueryParam("sex") String sex,
			@QueryParam("roles") String roles, @QueryParam("page") Integer pageIndex, @QueryParam("limit") Integer pageSize) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));

		String sqlWhere = " status<>-2 ";// 把标记为删除的数据滤掉
		// LOG.info("status="+status);
		if (!si.isAnonymous()) {
			Object us = si.getAttribute("userInfo");
			if (us != null) {// 如果没有登录就不设置运营商ID
				if (((User) us).type != 3) {
					sqlWhere += " and svrId=" + ((User) us).svrId;
				}
			}
		}
		// if (null != type && !("".equals(type)))
		// sqlWhere += " and type=" + type;
		if (null != status && !("".equals(status)))
			sqlWhere += " and status=" + status;
		if (null != name && (!"".equals(name.trim())))
			sqlWhere += " and userName like '%" + name.trim() + "%'";
		if (null != tel && (!"".equals(tel.trim())))
			sqlWhere += " and tel like '%" + tel.trim() + "%'";
		if (null != tel && (!"".equals(roles.trim())))
			sqlWhere += " and roles like '%" + roles.trim() + "%'";
		if (null != sex && !("".equals(sex)))
			sqlWhere += " and sex='" + sex + "'";
		LOG.info("userRs=" + sqlWhere);
		PanacheQuery<User> pageSp = User.find(sqlWhere);
		// PanacheQuery<ServiceProvider> pageSp = ServiceProvider.findAll();
		// LOG.info("pageSp.count()="+pageSp.count());
		// if (pageSp.count()>pageSize)
		if (pageIndex==null||pageIndex < 1)
			pageIndex = 1;
		if (pageSize==null|| pageSize< 1)
			pageSize = 20;
		pageSp.page(pageIndex - 1, pageSize);// pageIndex 在页面从1开始,但后台从0开始
		rm.data = pageSp.list();
		rm.count = pageSp.count();
		return rm;
	}

	// 认证对象,可以获取已经认证通过的用户信息
	@Inject
	SecurityIdentity si;

	/**
	 * 新增用户
	 */
	// @Path("add")
	@PUT
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Consumes(MediaType.APPLICATION_JSON) // 提交类型
	@Transactional
	public RetMsg add(User ue) {
		if (!si.isAnonymous()) {
			Object us = si.getAttribute("userInfo");
			if (us != null) {// 如果没有登录就不设置运营商ID
				ue.ispId = ((User) us).ispId;// 设置运营商ID
				ue.svrId = ((User) us).svrId;// 设置服务商ID
			}
		}
		// LOG.info(sp.toString());
		ue.id=null;
		ue.persist();// 提交到数据库
		ue.flush();// 更新到数据库
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		rm.obj = ue;
		return rm;
	}

	/**
	 * 更新用户
	 */
	// @Path("update")
	@POST
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Consumes(MediaType.APPLICATION_JSON) // 提交类型
	@Transactional
	public RetMsg update(User ue) {
		/*
		 * if (!si.isAnonymous()) { Object us = si.getAttribute("userInfo"); if (us !=
		 * null){// 如果没有登录就不设置运营商ID ue.ispId = ((User) us).ispId;// 设置运营商ID ue.svrId =
		 * ((User) us).svrId;// 设置服务商ID } }
		 */
		// LOG.info(ue.toString());
		ue.getEntityManager().merge(ue);
		ue.flush();// 更新到数据库
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		rm.obj = ue;
		return rm;
	}

	/**
	 * 删除用户 把电话设置为了电话+ID,清除登录密码
	 */
	@Path("{id}")
	@DELETE
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Transactional
	public RetMsg delete(@PathParam("id") int id) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		rm.count = User.update("status=-2,name=name||tel,tel=id,password='fengwenxue09876543212' where id = ?1", id);
		return rm;
	}

	/**
	 * 更新用户状态
	 */
	@Path("status/{id}/{status}")
	@GET
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Transactional
	public RetMsg status(@PathParam("id") int id, @PathParam("status") byte status) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		// LOG.info("status="+status +", id="+id);
		rm.count = User.update("status=?1 where id = ?2", status, id);
		return rm;
	}

	/**
	 * 修改指定用户密码
	 */
	@Path("password/{id}")
	@GET
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Transactional
	public RetMsg password(@PathParam("id") int id) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		// LOG.info("status="+status +", id="+id);
		rm.count = User.update("password='88888888' where id = ?1", id);
		return rm;
	}

	/**
	 * 修改自己用户密码
	 */
	@Path("ower_pass/{password}")
	@GET
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Transactional
	public RetMsg owerPass(@PathParam("password") String password) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		if (!si.isAnonymous()) {
			Object us = si.getAttribute("userInfo");
			if (us != null) {
				User ue = ((User) us);
				ue.password = password;
				// ue.flush();
				// int userId = ((User) us).id;//
				rm.code = "0";
				rm.count = User.update("password=?1 where id = ?2", password, ue.id);
				rm.msg = "修改用户密码成功";
			}
		} else {
			rm.code = "-1";
			rm.msg = "没有找到用户登录信息";
		}

		// LOG.info("status="+status +", id="+id);
		return rm;
	}

	/**
	 * 判断用户旧密码
	 */
	@Path("is_old/{password}")
	@GET
	@Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Transactional
	public RetMsg isOldPass(@PathParam("password") String password) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		Object us = si.getAttribute("userInfo");
		if (us != null) {
			User ue = ((User) us);
			 LOG.info("ue.password="+ue.password +", password="+password);
			if (ue.password .equals(password) ) {
				rm.code = "0";
				rm.msg = "密码正确";
			}else {
				rm.code = "1";
				rm.msg = "密码错误";
			}
		} else {
			rm.code = "-1";
			rm.msg = "没有找到用户登录信息";
		}

		
		return rm;
	}

	/**
	 * 获取操作用户
	 */
	@Path("getOwn")
	@GET
	// @Produces(MediaType.APPLICATION_JSON)
	public Object getOwn() {//
		return si.getAttribute("userInfo");
	}

	/**
	 * 判断用户手机是否重复
	 */
	@Path("unique/{tel}")
	@GET
	// @Produces(MediaType.APPLICATION_JSON)
	public RetMsg isUnique(@PathParam("tel") String tel) {//
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		User us = User.find("tel", tel).firstResult();
		//LOG.info("tel="+tel );
		if (null==us) {
			rm.code="0";
		}else {
			rm.code="1";
		}
		return rm;
	}
}
